package com.wolfheader.wolfgame.shiro;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.wolfheader.wolfgame.Principal;
import com.wolfheader.wolfgame.dao.admin.AdminDao;
import com.wolfheader.wolfgame.entity.admin.AdminEntity;
import com.wolfheader.wolfgame.entity.admin.RoleEntity;

public class AdminShiroRealm extends AuthorizingRealm {

	private static final Logger logger = LoggerFactory.getLogger(AdminShiroRealm.class);
	@Autowired
	private AdminDao adminDao;

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		logger.info("##################执行Shiro权限认证################## e10adc3949ba59abbe56e057f20f883e");
		// 获取当前登录输入的用户名，等价于(String)
		// principalCollection.fromRealm(getName()).iterator().next();
		Principal principal = (Principal) super.getAvailablePrincipal(principalCollection);
		AdminEntity admin = adminDao.findOne(principal.getId());
		if (admin != null) {
			// 权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			// 用户的角色集合
			info.setRoles(admin.getRolesName());
			// 用户的角色对应的所有权限，如果只使用角色定义访问权限，下面的四行可以不要
			for (RoleEntity role : admin.getRoles()) {
//				System.out.println(role.getPermissionsName());
				info.addStringPermissions(role.getPermissionsName());
			}
			// 或者按下面这样添加
			// 添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色
			// simpleAuthorInfo.addRole("admin");
			// 添加权限
			// simpleAuthorInfo.addStringPermission("admin:manage");
			// logger.info("已为用户[mike]赋予了[admin]角色和[admin:manage]权限");
			return info;
		}
		// 返回null的话，就会导致任何用户访问被拦截的请求时，都会自动跳转到unauthorizedUrl指定的地址
		return null;
	}

	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
			throws AuthenticationException {
		// UsernamePasswordToken对象用来存放提交的登录信息
		com.wolfheader.wolfgame.shiro.AuthenticationToken token = (com.wolfheader.wolfgame.shiro.AuthenticationToken) authenticationToken;
		String password = new String(token.getPassword());
		logger.info(
				"验证当前Subject时获取到token为：" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));

		// 查出是否有此用户
		AdminEntity admin = adminDao.findByUsername(token.getUsername());
		HttpSession session = token.getSession();
		if (admin != null) {
			session.setAttribute("currentAdminName", admin.getUsername());
			// 若存在，将此用户存放到登录认证info中，无需自己做密码对比，Shiro会为我们进行密码对比校验
			if (!StringUtils.equals(DigestUtils.md5Hex(password), admin.getPassword())) {
				// // 计算登录失败次数
				// int loginFailureCount = admin.getLoginFailureCount() + 1;
				// // 登录失败次数 >= 账户锁定计数，时
				// if (loginFailureCount >= setting.getAccountLockCount()) {
				// // 锁定管理员
				// admin.setLocked(true);
				// admin.setLockedDate(new Date());
				// }
				// admin.setLoginFailureCount(loginFailureCount);
				// adminService.update(admin);
				// 异常：认证错误
				throw new IncorrectCredentialsException();
			}

			if (admin.getEnabled() == false) {
				throw new IncorrectCredentialsException();
			}

			admin.setLoginIp(token.getHost());
			admin.setLoginDate(new Date());
			adminDao.save(admin);

			return new SimpleAuthenticationInfo(new Principal(admin.getId(), admin.getUsername()), password, getName());
		}
		return null;
	}

}
